import React, { useRef, useEffect } from 'react';
import BScroll, { Options } from '@better-scroll/core';
import Pullup from '@better-scroll/pull-up';
import PullDown from '@better-scroll/pull-down';
import ScrollBar from '@better-scroll/scroll-bar';
import { Spinning } from '@/design';
import styles from './Scroll.less';

BScroll.use(ScrollBar);

type IScroll = {
  config: Partial<Options>;
  onPullingDown?: () => Promise<any>;
  onPullingUp?: () => Promise<any>;
  hasMore?: boolean;
  hasHeader?: boolean;
  hasFooter?: boolean;
};

type Position = {
  x: number;
  y: number;
};

const defaultConfig = {
  scrollbar: {
    fade: true,
  },
  scrollY: true,
  click: true,
  dblclick: true,
  // preventDefaultException:{className:/(^|\s)swiper(\s|$)/}
};

const Scroll: React.FC<IScroll> = props => {
  const scrollRef = useRef<BScroll>();
  const wrapRef = useRef<HTMLDivElement>(null);

  /* 初始化滾動 */
  const initScroll = () => {
    const { config, onPullingDown, onPullingUp } = props;
    const newConfig: Options = { ...defaultConfig, ...config };
    const { pullDownRefresh, pullUpLoad } = newConfig;
    console.log(newConfig);
    pullUpLoad && BScroll.use(Pullup);
    pullDownRefresh && BScroll.use(PullDown);
    let bs = new BScroll(wrapRef.current as HTMLDivElement, newConfig);

    // 下拉刷新
    pullDownRefresh &&
      bs.on('pullingDown', () => {
        onPullingDown
          ? onPullingDown().finally(() => {
              bs.finishPullDown();
              bs.refresh();
            })
          : history.go(0);
      });

    // 上拉加載
    pullUpLoad &&
      bs.on('pullingUp', () => {
        onPullingUp &&
          onPullingUp().finally(() => {
            bs.finishPullUp();
            bs.refresh();
          });
      });

    // 滾動監聽
    // (pullDownRefresh || pullUpLoad) && bs.on('scroll', (pos: Position) => {
    //   // console.log(pos)
    // })

    scrollRef.current = bs;
  };

  useEffect(() => {
    // console.log(props.refresh)
    setTimeout(() => {
      initScroll();
    }, 0);
    return () => {
      // scrollRef.current && scrollRef.current.destroy()
    };
  }, []);

  return (
    <div
      ref={wrapRef}
      className={`${styles.wrapper} ${props.hasFooter ? styles.hasFooter : ''}`}
    >
      <div className={styles.content}>
        <div className={styles.pull_down}>
          <Spinning type="colors" size={16} />
        </div>
        {props.hasHeader && <div className={styles.hasHeader}></div>}
        <div className={styles.main}>{props.children}</div>
        <div className={styles.pull_Up}>
          {props.hasMore ? (
            <>
              <Spinning state="dark" type="circle" size={28} />
              <span className={styles.tips}>加載中…</span>
            </>
          ) : (
            <span>沒有了啦~</span>
          )}
        </div>
      </div>
    </div>
  );
};

export default Scroll;
